<template>
  <div class="strut-div" style="position: relative;">
    <div id="map_container" class="strut-div"></div>
    <div class="area-list">1111111111</div>

    <div class="area-introduce" :class="{'introduce-show':display,'introduce-hide':!display}">
      <h2>{{ activeObj.properties.name }}</h2>
      <p>{{ activeObj.properties.content }}</p>
    </div>
  </div>
</template>

<script>
import { initMap, isPointInPolygon } from '@/lib/map.js';
import { WgsToBd09 } from '@/lib/coordinate_transform.js';
import data from '../../../static/taigu.js';
import tg from '../../../static/tg.js';

import mapbg from '@/assets/imgs/tg/mapbg.png';

export default {
  data() {
    return {
      activeObj: {
        properties: {}
      },
      linesJson: [], //线条的Json数组
      areasJson: [], //区域的Json数组
      pointsJson: [], //活跃点的Json数组
      buildingJson: [], //虚拟建筑的Json数组
      map: null, //地图实体
      mainView: null, //地图主图层
      lineLayer: null, //线图层
      activeLineLayer: null, //当前活跃线图层
      activePointLayers: [null, null], //活跃点图层
      areaLayer: null, //区域图层
      activeAreaLayer: null, //当前活跃区域图层
      loopTimer: null, //循环轮播计时器
      activeIndex: 0, //当前活跃区域计数器
      animation: null,
      display:true,
    };
  },
  methods: {
    initBMap() {
      this.map = initMap({
        tilt: 55,
        heading: 10,
        // center: [111.6619029016793, 36.26090290026548],
        center: [112.74623376283817, 37.41472833735456],
        zoom: 12.4
        // zoom: 10.6
      });
      this.mainView = new mapvgl.View({
        effects: [
          // new mapvgl.BloomEffect({
          //   blurSize: 10
          // }),
          // new mapvgl.BlurEffect({
          //   blurSize: 10
          // }),
          new mapvgl.DepthEffect({
            blurSize: 10
          })
        ],
        map: this.map
      });
    },
    addAnimation() {
      let center = this.map.getCenter();
      let heading = this.map.getHeading();
      let tilt = this.map.getTilt();
      let zoom = this.map.getZoom();
      // console.log(center, zoom);
      this.animation = new BMapGL.ViewAnimation(
        [
          {
            center: new BMapGL.Point(center.lng, center.lat),
            heading: heading,
            tilt: tilt,
            zoom: zoom,
            percentage: 0
          },
          {
            center: new BMapGL.Point(center.lng, center.lat),
            heading: heading + 120,
            tilt: tilt - 15,
            zoom: zoom,
            percentage: 0.33
          },
          {
            center: new BMapGL.Point(center.lng, center.lat),
            heading: heading + 240,
            tilt: tilt + 5,
            zoom: zoom,
            percentage: 0.66
          },
          {
            center: new BMapGL.Point(center.lng, center.lat),
            heading: heading + 360,
            tilt: tilt,
            zoom: zoom,
            percentage: 1
          }
        ],
        {
          duration: 180000,
          delay: 0,
          interation: 'INFINITE'
        }
      );
      this.map.startViewAnimation(this.animation);
    },
    stopAnimation() {
      if (this.animation) {
        this.map.cancelViewAnimation(this.animation);
      }
    },
    addMapListener() {
      this.map.addEventListener('dragstart', event => {
        this.stopAnimation();
      });
      this.map.addEventListener('zoomstart', event => {
        this.stopAnimation();
      });

      this.map.addEventListener('dragend', event => {
        // console.log('dragend');
        setTimeout(this.addAnimation, 100);
        // this.addAnimation;
      });

      this.map.addEventListener('zoomend', event => {
        this.addAnimation();
      });
    },

    initJson() {
      data.features.map((item, index) => {
        this.areasJson.push({
          geometry: {
            type: 'Polygon',
            coordinates: item.geometry.coordinates
          },
          properties: {
            height: 1 // 多边形高度
          }
        });
        this.linesJson.push({
          geometry: {
            type: 'LineString',
            coordinates: item.geometry.coordinates[0]
          }
        });
      });
    },
    initLineLayer() {
      this.lineLayer = new mapvgl.SimpleLineLayer({
        // this.lineLayer = new mapvgl.WallLayer({
        // color: 'rgba(255, 71, 26, 0.8)',
        // color: '#2b3d7a',
        color: '#FFF',
        blend: 'lighter',
        data: this.linesJson,
        height: 300
      });
      this.mainView.addLayer(this.lineLayer);

      this.activeLineLayer = new mapvgl.WallTripLayer({
        // blend: 'lighter',
        step: 1.5,
        trailLength: 700,
        height: 200,
        color: 'rgb(0, 255, 255)'
      });
      this.mainView.addLayer(this.activeLineLayer);
    },
    //生成随机点图
    initPoints(number) {
      this.areasJson.map(area => {
        // console.log(area.geometry.coordinates[0].length);
        let number = Math.pow(area.geometry.coordinates[0].length, 2);

        let pointArr = [];
        area.geometry.coordinates[0].map(coord => {
          let point = new BMap.Point(coord[0], coord[1]);
          pointArr.push(point);
        });
        let polygon = new BMap.Polygon(pointArr);
        let bounds = polygon.getBounds();

        let pointsArray = [];

        for (var i = 0; i < 2; i++) {
          let points = [];
          while (points.length < number / 6) {
            let randomPoint = this.randomPoint(bounds);
            if (isPointInPolygon(randomPoint, polygon)) {
              points.push({
                geometry: {
                  type: 'Point',
                  coordinates: [randomPoint.lng, randomPoint.lat]
                },
                properties: {
                  time: Math.random() * 10,
                  count: Math.random() * 10
                }
              });
            }
          }
          pointsArray.push(points);
        }

        //生成随机建筑
        for (var i = 0; i < number / 400; i++) {
          let p = this.randomPoint(bounds);
          if (isPointInPolygon(p, polygon)) {
            this.buildingJson.push({
              type: 'Feature',
              properties: {
                height: Math.random() * 50
              },
              geometry: {
                type: 'Polygon',
                coordinates: [
                  [[p.lng - 0.003, p.lat - 0.003], [p.lng - 0.003, p.lat + 0.003], [p.lng + 0.003, p.lat + 0.003], [p.lng + 0.003, p.lat - 0.003], [p.lng - 0.003, p.lat - 0.003]]
                ]
              }
            });
          }
        }

        this.pointsJson.push(pointsArray);
      });
      // console.log(this.pointsJson);
    },
    randomPoint(bounds) {
      let sw = bounds.getSouthWest();
      let ne = bounds.getNorthEast();
      let point = new BMap.Point(sw.lng + Math.random() * (ne.lng - sw.lng), sw.lat + Math.random() * (ne.lat - sw.lat));
      return point;
    },
    initAreaLayer() {
      let layer = new mapvgl.ShapeLayer({
        opacity: 0.01,
        data: [tg],
        texture: mapbg,
        enablePreciseMap: true,
        // texture: 'https://mapv.baidu.com/gl/examples/images/light.jpg',
        isTextureFull: true
      });
      this.mainView.addLayer(layer);

      this.areaLayer = new mapvgl.ShapeLayer({
        // color: 'rgba(55, 55, 200, 0.1)',
        // blend: 'lighter',
        // style: 'normal',
        opacity: 0.01,
        data: this.areasJson
      });
      this.mainView.addLayer(this.areaLayer);

      this.activeAreaLayer = new mapvgl.ShapeLayer({
        // color: 'rgb(0, 255, 255)', // 面颜色
        // style: 'gradual',
        // style: 'windowAnimation',
        opacity: 0.2 // 透明度
      });
      this.mainView.addLayer(this.activeAreaLayer);

      this.activePointLayers[0] = new mapvgl.PointLayer({
        blend: 'lighter',
        shape: 'circle',
        // color: 'rgba(255, 77, 77, 0.4)', // 点图层1颜色
        color: 'rgba(255, 225, 0, 0.4)', // 点动画图层颜色
        size: 1
      });

      // this.activePointLayers[1] = new mapvgl.PointLayer({
      //   blend: 'lighter',
      //   shape: 'circle',
      //   color: 'rgba(255, 204, 0, 0.1)', // 点图层2颜色
      //   size: 1.5
      // });

      // this.activePointLayers[2] = new mapvgl.PointLayer({
      //   blend: 'lighter',
      //   shape: 'circle',
      //   color: 'rgba(255, 255, 0, 0.1)', // 点图层3颜色
      //   size: 2
      // });

      this.mainView.addLayer(this.activePointLayers[0]);
      // this.mainView.addLayer(this.activePointLayers[1])
      // this.mainView.addLayer(this.activePointLayers[2])
      // this.mainView.addLayer(this.activePointLayers[3])

      let buidingLayer = new mapvgl.ShapeLayer({
        // style: 'window',
        blend: 'lighter',
        // rippleLayer: rippleLayer,
        texture: 'https://mapv.baidu.com/gl/examples/images/light.jpg',
        // isTextureFull: true,
        // textureScale: 1,
        // topColor: 'rgba(39, 50, 85, 1)',
        isTextureFull: true,
        color: [0.8, 0.8, 0.1],
        opacity: 0.1
      });

      this.mainView.addLayer(buidingLayer);
      // buidingLayer.setData(this.buildingJson);
    },
    showActiveLayer(index) {

      this.display = false;

      setTimeout(()=>{


        this.activeLineLayer.setData([this.linesJson[index]]);
        let currentArea = JSON.parse(JSON.stringify(this.areasJson[index]));
        this.activeAreaLayer.setData([currentArea]);


        if (this.activePointLayers[1]) {
          this.mainView.removeLayer(this.activePointLayers[1]);
        }

        // this.activePointLayers[1] = new mapvgl.PointTripLayer({
        this.activePointLayers[1] = new mapvgl.HeatPointLayer({
          gradient: {
            0.0: 'rgb(50, 50, 256)',
            0.1: 'rgb(50, 250, 56)',
            0.5: 'rgb(250, 250, 56)',
            1.0: 'rgb(250, 50, 56)'
          },
          blend: 'lighter',
          shape: 'circle',
          startTime: 0,
          endTime: 20,
          step: 0.02,
          trailLength: 10,
          color: 'rgba(250, 50, 56,1)', // 点动画图层颜色
          // color: 'rgba(255, 77, 77, 0.5)', // 点图层1颜色
          size: 2
        });
        this.mainView.addLayer(this.activePointLayers[1]);

        for (var i = 0; i < this.activePointLayers.length; i++) {
          this.activePointLayers[i].setData(this.pointsJson[index][i]);
        }


        if (this.activeIndex == this.linesJson.length - 1) {
          this.activeIndex = 0;
        } else {
          this.activeIndex++;
        }

        this.activeObj = data.features[this.activeIndex];



        this.display = true;
      }, 1400);


    },
    startLoop() {
      if (!this.loopTimer) {
        this.showActiveLayer(this.activeIndex);
        this.loopTimer = setInterval(() => {
          this.showActiveLayer(this.activeIndex);
        }, 15000);
      }
    },
    stopLoop() {
      clearInterval(this.loopTimer);
      this.loopTimer = null;
    },
    riseArea(area) {
      let timer = setInterval(() => {
        area.properties.height += 30;
        if (area.properties.height < 3000) {
          this.activeAreaLayer.setData([area]);
        } else {
          clearInterval(timer);
        }
      }, 100);
    }
  },
  mounted() {
    this.initBMap();
    this.initJson();
    this.initPoints(2000);

    this.initLineLayer();
    this.initAreaLayer();
    this.startLoop();

    // this.initRoad();

    setTimeout(() => {
      this.addAnimation();
      this.addMapListener();
    }, 2000);

    let THREE = mapvgl.THREE;
    // console.log(THREE);
  },
  beforeDestroy() {
    this.stopLoop();
  }
};
</script>

<style>
.area-list {
  position: absolute;
  width: 300px;
  top: 0;
  bottom: 0;
  background-color: #fff;
}
.area-introduce {
  position: absolute;
  border: 0;
  width: 400px;
  /* height: 200px; */
  right: 100px;
  top: 100px;
  border-radius: 10px;
  padding: 15px;
  color: #000;
  background-color: #FFF;
  opacity: 0.8;
  transition: opacity 0.7s;
}
.introduce-show {
  opacity: 0.8;
}

.introduce-hide {
  opacity: 0;
}
</style>
